package com.hbnu.service;

import com.hbnu.dao.UserDAO;
import com.hbnu.entity.User;

public class UserService {
    private UserDAO userDAO = new UserDAO();

    // 用户注册
    public void register(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (userDAO.existsUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        if (!userDAO.register(user)) {
            throw new RuntimeException("注册失败，请重试");
        }
    }

    // 用户登录
    public User login(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }

        User user = userDAO.login(username, password);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        return user;
    }
}